package com.ideal.hadoopadmin.web.interceptor;

import com.ideal.hadoopadmin.entity.main.Menu;
import com.ideal.hadoopadmin.entity.main.User;
import com.ideal.hadoopadmin.entity.meta.hdfs.MetaHdfsInfo;
import com.ideal.hadoopadmin.entity.system.WebLog;
import com.ideal.hadoopadmin.entity.system.WebOperations;
import com.ideal.hadoopadmin.framework.web.HttpRequests;
import com.ideal.hadoopadmin.service.main.SystemMenuService;
import com.ideal.hadoopadmin.service.meta.hdfs.MetaHdfsInfoBakService;
import com.ideal.hadoopadmin.service.meta.hdfs.MetaHdfsInfoService;
import com.ideal.hadoopadmin.service.system.WebLogService;
import com.ideal.hadoopadmin.service.system.WebOperationsService;
import com.ideal.hadoopadmin.web.controller.UIController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 * Created by CC on 2016/2/16.
 */
public class UIInterceptors extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(UIInterceptors.class);

    @Resource
    SystemMenuService systemMenuService;
    @Resource
    WebLogService webLogService;
    @Resource
    WebOperationsService webOperationsService;
    @Resource
    MetaHdfsInfoBakService metaHdfsInfoBakService;
    @Resource
    MetaHdfsInfoService metaHdfsInfoService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return super.preHandle(request, response, handler);
    }

    @Override
    /**
     * 拦截具体需求
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        /*这里可以针对所有的Controller做一些统一处理 */
        if (handler instanceof HandlerMethod) {
            if (((HandlerMethod) handler).getBean() instanceof UIController) {
                UIController controller = (UIController) ((HandlerMethod) handler).getBean();
                String portalPrefix = controller.getPortalPrefix();
                request.setAttribute("portalPrefix", portalPrefix);
                if (!portalPrefix.startsWith("/")) {
                    request.setAttribute("portalPrefix", "/" + portalPrefix);
                }
            }
        }
        //排序参数
        Map<String, Object> searchParams = HttpRequests.getParametersStartingWith(request, "Q_");
        request.setAttribute("sortType", request.getParameter("sortType"));
        request.setAttribute("searchParams", HttpRequests.encodeParameterStringWithPrefix(searchParams, "Q_"));


        //1.获取菜单信息
        //  这个值默认是每次都刷新菜单。（可能要修改下 根据具体的请求来确定是否需要刷新菜单！）
        String isFreshMenu = (String) request.getAttribute("isFreshMenu");
        if (isFreshMenu == null || isFreshMenu.trim().length() == 0 || isFreshMenu.equals("true")) {
            getMenuList(request, response, handler, modelAndView);
        }

        //2.***********日志入库 ************
        Enumeration<String> enumeration = request.getParameterNames();
        String param = "";

        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getParameter(key);
            if (value != null && !value.equals("")) {
                param = param + key + ":" + value + ",";
            }
        }


        if (param.length() > 1) {
            param = param.substring(0, param.length() - 1);
        }
        //拦截当前系统时间；
        Date date = new Date();
        //拦截url
        String path3 = request.getServletPath();

        //拦截登录用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        String name = user.getUserName();
        WebLog webLog = new WebLog();
        webLog.setCreatetime(date.getTime());
        WebOperations webOperations = webOperationsService.queryWebOperationsByOperationName(path3);
        if (webOperations == null) {
            WebOperations wo = new WebOperations();
            wo.setUrl(path3);
            webOperationsService.saveWebOperations(wo);
            webLog.setOperationId(wo.getId());
        } else {
            webLog.setOperationId(webOperations.getId());
        }
        webLog.setUserName(name);
        webLog.setParameter(param);
        webLogService.saveWebLog(webLog);

        /*事件数量统计*/
        postHandle2(request,response,handler,modelAndView);
    }


    /**
     * 初始化系统菜单
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    private void getMenuList(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String requestUri = request.getServletPath();
        List<Menu> menuList = systemMenuService.getLoginUserMenu(requestUri);
        request.setAttribute("menuList", menuList);
    }

    public void postHandle2(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //事件同步数量
//        Integer count = eventInfoService.getEventInfo();
//        if (0 != count) {
//            request.setAttribute("count", count);
//        }

//        //kerberos刷新数量
//        Integer countKerberos = kerberosService.findAllKerberos();
//        if (0 != countKerberos) {
//            request.setAttribute("countKerberos", countKerberos);
//        }

        //HDFS警报数量
//        List list1 = hdfsInfoBakService.findAllHDFS("db", null);
//        List list2 = hdfsInfoBakService.findAllHDFS("hdfs", null);
       /* List list1 = metaHdfsInfoBakService.compareWithHdfsInfo();
        List list2 = metaHdfsInfoService.compareWithHdfsInfoBak();
        Integer countHDFS = list1.size() + list2.size();
        if (0 != countHDFS) {
            request.setAttribute("countHDFS", countHDFS);
        }*/

    }

}
